#include "ThreadedLocalProcessor.h"
#include <pthread.h>

namespace ComputingObjects
{

ThreadedLocalProcessor::ThreadedLocalProcessor()
{
}

ThreadedLocalProcessor::~ThreadedLocalProcessor()
{
}

class WorkUnitThread : public WorkUnitObserver
{
public:
	WorkUnitThread(SharedWorkUnit unit)
		: myUnit(unit)
		{};
		
	pthread_t myThread;
	SharedWorkUnit myUnit;
	
	static void* thread_main(void* arg)
	{
		WorkUnitThread* me = (WorkUnitThread*) arg;
		// Space out the WU's for fun
		sleep(1+ (rand() % 5));
		while (me->myUnit->getState() != WorkUnit::completed)
			me->myUnit->compute();
		return NULL;
	}
	void stateChange(WorkUnit& unit, enum WorkUnit::state oldState) {};
};

void ThreadedLocalProcessor::execute(SharedWorkUnit unit)
{
	std::tr1::shared_ptr<WorkUnitThread> obs(new WorkUnitThread(unit));
	pthread_create(&obs->myThread, NULL, WorkUnitThread::thread_main, obs.get());
	unit->attach(obs);
}

}
